package com.jsh.erp.service.WorkflowConfigProcess;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.NotAuditDepotHead;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.dailyHead.DailyHeadService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.msg.MsgService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class WorkflowConfigProcessService {
    private Logger logger = LoggerFactory.getLogger(WorkflowConfigProcessService.class);

    @Resource
    private WorkflowProcessDetailMapper workflowProcessDetailMapper;
    @Resource
    private WorkflowProcessDetailMapperEx workflowProcessDetailMapperEx;
    @Resource
    private WorkflowApproveDetailMapper workflowApproveDetailMapper;
    @Resource
    private WorkflowConfigMainMapper workflowConfigMainMapper;
    @Resource
    private LogService logService;
    @Resource
    private RedisService redisService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WorkflowConfigDetailMapper workflowConfigDetailMapper;
    @Resource
    private WorkflowProcessDetailHisMapper workflowProcessDetailHisMapper;
    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private MsgService msgService;
    @Resource
    private DepotItemService depotItemService;
    @Resource
    private DailyHeadService dailyHeadService;
    @Resource
    private AuditSynchronizationMapper auditSynchronizationMapper;
    @Resource
    private SupplierService supplierService;
    @Resource
    private UserMapperEx userMapperEx;
    @Resource
    private WorkflowConfigMainMapperEx workflowConfigMainMapperEx;
    @Resource
    private SynchronizationTaskMapperEx synchronizationTaskMapperEx;

    public WorkflowProcessDetail getWorkflowConfigProcess(String id) throws Exception {
        return workflowProcessDetailMapper.selectByPrimaryKey(id);
    }

    public List<WorkflowProcessDetail> select(String taskTitle, int offset, int rows) throws Exception {
        List<WorkflowProcessDetail> list = null;
//        try {
//            list = workflowProcessDetailMapperEx.selectByMainId(taskTitle,offset, rows);
//        } catch (Exception e) {
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
        return list;
    }

    public Long countWorkflowConfigProcess(String taskTitle) throws Exception {
        Long result = null;
//        try {
//            result = workflowProcessDetailMapperEx.countsByMainId(taskTitle);
//        } catch (Exception e) {
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertWorkflowConfigProcess(JSONObject obj, HttpServletRequest request) throws Exception {
        WorkflowProcessDetail workflowConfigDetail = JSONObject.parseObject(obj.toJSONString(), WorkflowProcessDetail.class);
        workflowConfigDetail.setId(IdUtils.getUUID());
        workflowConfigDetail.setUploadFlag("0");
        int result = 0;
        try {
            result = workflowProcessDetailMapper.insertSelective(workflowConfigDetail);
            logService.insertLog("分配权限",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(workflowConfigDetail.getTaskTitle()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateWorkflowConfigProcess(JSONObject obj, HttpServletRequest request) throws Exception {
        WorkflowProcessDetail workflowConfigDetail = JSONObject.parseObject(obj.toJSONString(), WorkflowProcessDetail.class);
        workflowConfigDetail.setUploadFlag("0");
        int result = 0;
        try {
            result = workflowProcessDetailMapper.updateByPrimaryKeySelective(workflowConfigDetail);
            logService.insertLog("分配权限",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(workflowConfigDetail.getTaskTitle()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteWorkflowConfigProcess(String id, HttpServletRequest request) throws Exception {
        return batchDeleteWorkflowProcessDetailByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteWorkflowConfigProcess(String ids, HttpServletRequest request) throws Exception {
        return batchDeleteWorkflowProcessDetailByIds(ids);
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteWorkflowProcessDetailByIds(String ids) throws Exception {
        int result = 0;
//        String [] idArray=ids.split(",");
        //TODO 校检 流程配置表
//        List<Material> materialList=null;
//        try{
//            materialList=materialMapperEx.getMaterialListByUnitIds(idArray);
//        }catch(Exception e){
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
//        if(materialList!=null&&materialList.size()>0){
//            logger.error("异常码[{}],异常提示[{}],参数,UnitIds[{}]",
//                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,"zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US,ids);
//            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
//                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US);
//        }
//        //记录日志
//        StringBuffer sb = new StringBuffer();
//        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
//        List<Unit> list = getUnitListByIds(ids);
//        for(Unit unit: list){
//            sb.append("[").append(unit.getName()).append("]");
//        }
//        logService.insertLog("流程设计", sb.toString(),
//                StringUtil.getRequest());
//        User userInfo=userService.getCurrentUser();
//        //校验通过执行删除操作
//        try{
//            result=unitMapperEx.batchDeleteUnitByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
//        }catch(Exception e){
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception {
        WorkflowProcessDetailExample example = new WorkflowProcessDetailExample();
        example.createCriteria().andIdNotEqualTo(id).andTaskTitleEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<WorkflowProcessDetail> list = null;
        try {
            list = workflowProcessDetailMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list == null ? 0 : list.size();
    }

    /**
     * @Author: wy
     * @Description: 待审批任务
     * @DateTime: 2022/7/29 16:20
     * @Params:
     * @Return
     */
    public List<WorkflowProcessDetail> selectByCreate(String taskTitle, String userId, int offset, int rows,String flowKey) throws Exception {
        List<WorkflowProcessDetail> list = null;
        try {
            list = workflowProcessDetailMapperEx.selectByMainId(taskTitle, userId, offset, rows,flowKey);
            for (WorkflowProcessDetail detail:list){
                detail.setCreateDateStr(Tools.getCenternTime(detail.getCreateDate()));
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countByCreate(String taskTitle, String userId,String flowKey) throws Exception {
        Long result = null;
        try {
            result = workflowProcessDetailMapperEx.countsByMainId(taskTitle, userId,flowKey);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
     * @Author: wy
     * @Description: 审批历史
     * @DateTime: 2022/7/29 16:21
     * @Params:
     * @Return
     */
    public List<WorkflowProcessDetailHis> getHistoryInfo(String defineDetailId) throws Exception {
        List<WorkflowProcessDetailHis> list = null;
        try {
            list = workflowProcessDetailMapperEx.selectByDefinId(defineDetailId);
            for (WorkflowProcessDetailHis detail:list){
                detail.setCreateDateStr(detail.getCreateDate() ==null ? "" : Tools.getCenternTime(detail.getCreateDate()));
                detail.setLastUpdateDateStr(detail.getLastUpdateDate() ==null ? "" : Tools.getCenternTime(detail.getLastUpdateDate()));
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
    * @Author: wy
    * @Description: 待审核数量
    * @DateTime: 2022-12-19 16:41
    * @Params:
    * @Return
    */
    public Long reviewedNumber(String creator) throws Exception {
        Long number = null;
        try {
            number = workflowProcessDetailMapperEx.countByCreate(creator);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return number;
    }

    public List<NotAuditDepotHead> notAuditSubTypeCount(String creator) throws Exception {
        List<NotAuditDepotHead> depotHeadList = null;
        try {
            depotHeadList = workflowProcessDetailMapperEx.notAuditSubTypeCount(creator);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depotHeadList;
    }

    /**
     * @Author: wy
     * @Description: 已审批任务
     * @DateTime: 2022/7/29 16:20
     * @Params:
     * @Return
     */
    public List<WorkflowApproveDetail> selectApproveByCreate(String taskTitle, String userId, int offset, int rows,String flowKey) throws Exception {
        List<WorkflowApproveDetail> list = null;
        try {
            list = workflowProcessDetailMapperEx.selectApproveByCreate(taskTitle, userId, offset, rows,flowKey);
            for (WorkflowApproveDetail detail:list){
                detail.setBeginDateStr(Tools.getCenternTime(detail.getBeginDate()));
                detail.setApproveDateStr(Tools.getCenternTime(detail.getApproveDate()));
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countApproveByCreate(String taskTitle, String userId,String flowKey) throws Exception {
        Long result = null;
        try {
            result = workflowProcessDetailMapperEx.countApproveByCreate(taskTitle, userId,flowKey);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
    * @Author: wy
    * @Description: 驳回单据
    * @DateTime: 2022-12-19 14:40
    * @Params:
    * @Return
    */
    public List<WorkflowApproveDetail> rejectApproveList(String taskTitle, String userId, int offset, int rows,String flowKey) throws Exception {
        List<WorkflowApproveDetail> list = null;
        try {
            list = workflowProcessDetailMapperEx.rejectApproveList(taskTitle, userId, offset, rows,flowKey);
            for (WorkflowApproveDetail detail:list){
                detail.setBeginDateStr(Tools.getCenternTime(detail.getBeginDate()));
                detail.setApproveDateStr(Tools.getCenternTime(detail.getApproveDate()));
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long rejectApproveCount(String taskTitle, String userId,String flowKey) throws Exception {
        Long result = null;
        try {
            result = workflowProcessDetailMapperEx.rejectApproveCount(taskTitle, userId,flowKey);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    /**
     * @Author: wy
     * @Description: 审批
     * @DateTime: 2022/7/30 9:31
     * @Params:
     * @Return
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void batchApproveType(String approveType, String ids, String approveMsg, HttpServletRequest request) throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        String userId = redisService.getObjectFromSessionByKey(request, "userId").toString();
        User user = userMapper.selectByPrimaryKey(userId);
        String lanCode = redisService.getLanCodeFromSession(request);
        String token = request.getHeader("X-Access-Token");
        String tenantId = Tools.getTenantIdByToken(token);
        for (String id : idList) {
            //新增审批明细
            WorkflowProcessDetail processDetail = workflowProcessDetailMapperEx.selectById(id);
            if (!userId.equals(processDetail.getCreateBy())) {
                throw new BusinessRunTimeException(ExceptionConstants.WORKFLOW_AUDIT_CODE,
                        "zh".equals(lanCode) ? ExceptionConstants.WORKFLOW_AUDIT_MSG : ExceptionConstants.WORKFLOW_AUDIT_MSG_US);
            }
            if (!tenantId.equals(processDetail.getTenantId())) {
                addAuditSynchronization(processDetail,processDetail.getAttribute2(),approveType,approveMsg,processDetail.getCreateBy());
                // 待审批任务需要删除
                workflowProcessDetailMapperEx.deleteById(processDetail.getId());
            } else {
                String defineDetailId = processDetail.getDefineDetailId();
                WorkflowConfigMain workflowConfigMain = workflowConfigMainMapper.selectByPrimaryKey(defineDetailId);
                //新增审批记录
                WorkflowApproveDetail approveDetail = new WorkflowApproveDetail();
                approveDetail.setId(IdUtils.getUUID());
                approveDetail.setTaskTitle(processDetail.getTaskTitle());
                approveDetail.setProcessDetailId(processDetail.getId());
                approveDetail.setApproveAccount(userId);
                approveDetail.setApproveName(user.getLoginName());
                approveDetail.setApproveMsg(approveMsg);
                approveDetail.setApproveType(approveType);
                approveDetail.setBeginDate(processDetail.getCreateDate());
                approveDetail.setApproveDate(new Date());
                approveDetail.setProcess(processDetail.getProcess());
                approveDetail.setAttribute1(processDetail.getAttribute1());
                approveDetail.setAttribute2(processDetail.getAttribute2());
                approveDetail.setConfigId(processDetail.getDefineDetailId());
                approveDetail.setSysOwnerCpy(processDetail.getSysOwnerCpy());
                approveDetail.setFlowKey(processDetail.getFlowKey());
                approveDetail.setUploadFlag("0");
                workflowApproveDetailMapper.insertSelective(approveDetail);

                //新增审批历史
                WorkflowProcessDetailHis processDetailHis = new WorkflowProcessDetailHis();
                processDetailHis.setId(IdUtils.getUUID());
                processDetailHis.setTaskTitle(processDetail.getTaskTitle());
                processDetailHis.setDefineDetailId(processDetail.getId());
                processDetailHis.setFlowKey(processDetail.getFlowKey());
                processDetailHis.setCreateBy(processDetail.getCreateBy());
                processDetailHis.setCreateDate(new Date());
                processDetailHis.setLastUpdateDate(new Date());
                processDetailHis.setAttribute1(processDetail.getAttribute1());
                processDetailHis.setEnableFlag(approveType);
                processDetailHis.setUploadFlag("0");
                processDetailHis.setRmk(approveMsg);
                workflowProcessDetailHisMapper.insertSelective(processDetailHis);
                if (BusinessConstants.APPROVE_TYPE_PASS.equals(approveType)) {
                    //判断流程到第几步 未完成新增 完成即修改单据状态
                    if (workflowConfigMain.getStep() > processDetail.getProcess()) {
                        addWorkProcessDetail(workflowConfigMain.getId(), processDetail);
                        //审核别人的要新增到审核同步
//                    if (user==null){
//                        addAuditSynchronization("0",processDetail,processDetailHis,processDetailHis.getId(),processDetail.getAttribute2(),approveType);
//                    }
                    } else {

                        //单据状态
                        if ("accountHead".equals(processDetail.getAttribute2())) {
                            accountHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                        } else if ("depotHead".equals(processDetail.getAttribute2())) {
                            depotHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                            //更新当前库存
                            depotItemService.updateCurrentStockByHeaderId(processDetail.getBusinessKey(),true);
                            //修改关联订单状态
                            depotHeadService.changeBillStatus(processDetail.getBusinessKey());
                            //盘点单状态
                            depotItemService.getTakeStockDepotHead(processDetail.getBusinessKey());

                        } else if ("dailyHead".equals(processDetail.getAttribute2())) {
                            dailyHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                        }
                        // 待审批任务需要删除
                        workflowProcessDetailMapper.deleteByPrimaryKey(processDetail.getId());
                        addWorkProcessDetail(workflowConfigMain.getId(), processDetail);
                        //审核别人的要新增到审核同步
//                    if (user==null){
//                        addAuditSynchronization("1",processDetail,processDetailHis,processDetailHis.getId(),processDetail.getAttribute2(),approveType);
//                    }
                    }
                } else if (BusinessConstants.APPROVE_TYPE_REJECT.equals(approveType)) {
                    //驳回 修改状态 重新审核
                    if ("accountHead".equals(processDetail.getAttribute2())) {
                        accountHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                    } else if ("depotHead".equals(processDetail.getAttribute2())) {
                        depotHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                    } else if ("dailyHead".equals(processDetail.getAttribute2())) {
                        dailyHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                    }
                    // 待审批任务需要删除
                    workflowProcessDetailMapper.deleteByPrimaryKey(processDetail.getId());
                    //审核别人的要新增到审核同步
//                if (user==null){
//                    addAuditSynchronization("2",processDetail,processDetailHis,processDetailHis.getId(),processDetail.getAttribute2(),approveType);
//                }
                }
                //新增消息给当前用户的租户或租户自己
                msgService.insertMsgByWork(approveDetail.getSysOwnerCpy(), approveMsg, approveType, request);
            }
        }
    }
    /**
    * @Author: wy
    * @Description: 同步回来时，做处理的审批
    * @DateTime: 2023-02-14 20:02
    * @Params:
    * @Return
    */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void ApproveType(String approveType, String ids, String approveMsg, String userId) throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        User user = userMapperEx.getUserById(userId);
        for (String id : idList) {
            //新增审批明细
            WorkflowProcessDetail processDetail = workflowProcessDetailMapperEx.selectById(id);
            String defineDetailId = processDetail.getDefineDetailId();
            WorkflowConfigMain workflowConfigMain = workflowConfigMainMapperEx.selectById(defineDetailId);
            //新增审批记录
            WorkflowApproveDetail approveDetail = new WorkflowApproveDetail();
            approveDetail.setId(IdUtils.getUUID());
            approveDetail.setTaskTitle(processDetail.getTaskTitle());
            approveDetail.setProcessDetailId(processDetail.getId());
            approveDetail.setApproveAccount(userId);
            approveDetail.setApproveName(user.getLoginName());
            approveDetail.setApproveMsg(approveMsg);
            approveDetail.setApproveType(approveType);
            approveDetail.setBeginDate(processDetail.getCreateDate());
            approveDetail.setApproveDate(new Date());
            approveDetail.setProcess(processDetail.getProcess());
            approveDetail.setAttribute1(processDetail.getAttribute1());
            approveDetail.setAttribute2(processDetail.getAttribute2());
            approveDetail.setConfigId(processDetail.getDefineDetailId());
            approveDetail.setSysOwnerCpy(processDetail.getSysOwnerCpy());
            approveDetail.setFlowKey(processDetail.getFlowKey());
            approveDetail.setUploadFlag("0");
            workflowApproveDetailMapper.insertSelective(approveDetail);

            //新增审批历史
            WorkflowProcessDetailHis processDetailHis = new WorkflowProcessDetailHis();
            processDetailHis.setId(IdUtils.getUUID());
            processDetailHis.setTaskTitle(processDetail.getTaskTitle());
            processDetailHis.setDefineDetailId(processDetail.getId());
            processDetailHis.setFlowKey(processDetail.getFlowKey());
            processDetailHis.setCreateBy(processDetail.getCreateBy());
            processDetailHis.setCreateDate(new Date());
            processDetailHis.setLastUpdateDate(new Date());
            processDetailHis.setAttribute1(processDetail.getAttribute1());
            processDetailHis.setEnableFlag(approveType);
            processDetailHis.setUploadFlag("0");
            processDetailHis.setRmk(approveMsg);
            workflowProcessDetailHisMapper.insertSelective(processDetailHis);
            if (BusinessConstants.APPROVE_TYPE_PASS.equals(approveType)) {
                //判断流程到第几步 未完成新增 完成即修改单据状态
                if (workflowConfigMain.getStep() > processDetail.getProcess()) {
                    addWorkProcessDetail(workflowConfigMain.getId(), processDetail);
                } else {
                    //单据状态
                    if ("accountHead".equals(processDetail.getAttribute2())) {
                        accountHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                    } else if ("depotHead".equals(processDetail.getAttribute2())) {
                        depotHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                        //更新当前库存
                        depotItemService.updateCurrentStockByHeaderId(processDetail.getBusinessKey(),true);
                        //修改关联订单状态
                        depotHeadService.changeBillStatus(processDetail.getBusinessKey());
                        //盘点单状态
                        depotItemService.getTakeStockDepotHead(processDetail.getBusinessKey());

                    } else if ("dailyHead".equals(processDetail.getAttribute2())) {
                        dailyHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_AUDIT, processDetail.getBusinessKey());
                    }
                    // 待审批任务需要删除
                    workflowProcessDetailMapperEx.deleteById(processDetail.getId());
                }
            } else if (BusinessConstants.APPROVE_TYPE_REJECT.equals(approveType)) {
                //驳回 修改状态 重新审核
                if ("accountHead".equals(processDetail.getAttribute2())) {
                    accountHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                } else if ("depotHead".equals(processDetail.getAttribute2())) {
                    depotHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                } else if ("dailyHead".equals(processDetail.getAttribute2())) {
                    dailyHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_REJECT, processDetail.getBusinessKey());
                }
                // 待审批任务需要删除
                workflowProcessDetailMapperEx.deleteById(processDetail.getId());
            }
            //新增消息给当前用户的租户或租户自己
//                msgService.insertMsgByWork(approveDetail.getSysOwnerCpy(), approveMsg, approveType, request);
        }

    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addAuditSynchronization(WorkflowProcessDetail processDetail,String type,String approveType,String approveMsg,String createBy) throws Exception {
        try {
            AuditSynchronizationExample example=new AuditSynchronizationExample();
            example.createCriteria().andProcessIdEqualTo(processDetail.getId())
                    .andCustom2EqualTo(type).andCreateByEqualTo(createBy).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<AuditSynchronization> auditSynchronizations = auditSynchronizationMapper.selectByExample(example);
            if (null !=auditSynchronizations && auditSynchronizations.size()>0){
                AuditSynchronization auditSynchronization = auditSynchronizations.get(0);
                auditSynchronization.setUploadFlag("0");
                auditSynchronization.setApproveType(approveType);
                auditSynchronization.setApproveMsg(approveMsg);
                auditSynchronizationMapper.updateByPrimaryKeySelective(auditSynchronization);
            }else {
                AuditSynchronization auditSynchronization= new AuditSynchronization();
                auditSynchronization.setId(IdUtils.getUUID());
                auditSynchronization.setProcessId(processDetail.getId());
                auditSynchronization.setCreateBy(createBy);
                auditSynchronization.setCustom1(processDetail.getTenantId());
                auditSynchronization.setCustom2(type);
                auditSynchronization.setApproveType(approveType);
                auditSynchronization.setApproveMsg(approveMsg);
                auditSynchronization.setUploadFlag("0");
                auditSynchronization.setCreateTime(new Date());
                auditSynchronizationMapper.insertSelective(auditSynchronization);
            }
        } catch (Exception e) {

            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional
    public void batchDeApproveType(String ids, HttpServletRequest request) throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        String userId = redisService.getObjectFromSessionByKey(request, "userId").toString();
        User user = userMapper.selectByPrimaryKey(userId);
        String lanCode = redisService.getLanCodeFromSession(request);
        for (String id : idList) {
            //新增审批明细
//            WorkflowProcessDetail processDetail = getWorkflowConfigProcess(id);
//            if (!userId.equals(processDetail.getCreateBy())) {
//                throw new BusinessRunTimeException(ExceptionConstants.DE_WORKFLOW_AUDIT_CODE,
//                        "zh".equals(lanCode) ? ExceptionConstants.DE_WORKFLOW_AUDIT_MSG:ExceptionConstants.DE_WORKFLOW_AUDIT_MSG_US);
//            }
//            if ("accountHead".equals(processDetail.getAttribute2())) {
                AccountHead accountHead = accountHeadService.getAccountHead(id);
                Boolean bo = accountHeadService.selectSuperStatus(accountHead);
                if(bo){
                    accountHeadService.batchSetStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT,id);
                }else {
                    throw new BusinessRunTimeException(ExceptionConstants.COUNTER_AUDIT_FAIL_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.COUNTER_AUDIT_FAIL_MSG : ExceptionConstants.COUNTER_AUDIT_FAIL_US);
                }
//            }else {
//                throw new BusinessRunTimeException(ExceptionConstants.WRONG_DOCUMENT_TYPE,
//                        "zh".equals(lanCode) ? ExceptionConstants.WRONG_DOCUMENT_TYPE_MSG:ExceptionConstants.WRONG_DOCUMENT_TYPE_MSG_US);
//            }
        }

    }

    /**
     * @Author: wy
     * @Description: 没结束继续 新增流程
     * @DateTime: 2022/7/30 9:31
     * @Params:
     * @Return
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addWorkProcessDetail(String id, WorkflowProcessDetail workflowProcessDetail) throws Exception {
        try {
            WorkflowConfigDetailExample example1 = new WorkflowConfigDetailExample();
            example1.createCriteria().andMainIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andProcessEqualTo(workflowProcessDetail.getProcess() + 1);
            List<WorkflowConfigDetail> workflowConfigDetails = workflowConfigDetailMapper.selectByExample(example1);
            if (workflowConfigDetails != null && workflowConfigDetails.size() > 0) {
                WorkflowConfigDetail detail = workflowConfigDetails.get(0);
                //第1步
                workflowProcessDetail.setProcess(detail.getProcess());
                workflowProcessDetail.setCreateBy(detail.getTypeValue());
                workflowProcessDetail.setCreateDate(new Date());
                workflowProcessDetail.setLastUpdateDate(new Date());
                workflowProcessDetail.setAttribute1(detail.getActivityName());
                workflowProcessDetail.setUploadFlag("0");
                workflowProcessDetailMapper.updateByPrimaryKeySelective(workflowProcessDetail);

            }
        } catch (Exception e) {

            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    /**
     * @Author: wy
     * @Description: 任务进度
     * @DateTime: 2022/7/30 14:24
     * @Params:defineDetailId 任务id
     * @Params:processDetailId 待审批id
     * @Return
     */
    public List<WorkflowConfigDetail> getProgressInfo(String defineDetailId, String processDetailId) throws Exception {
        WorkflowConfigDetailExample example1 = new WorkflowConfigDetailExample();
        example1.createCriteria().andMainIdEqualTo(defineDetailId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example1.setOrderByClause("process asc");
        List<WorkflowConfigDetail> workflowConfigDetails = workflowConfigDetailMapper.selectByExample(example1);
        if (workflowConfigDetails.size() > 0) {
            for (WorkflowConfigDetail detail : workflowConfigDetails) {
                WorkflowApproveDetailExample example = new WorkflowApproveDetailExample();
                example.createCriteria().andConfigIdEqualTo(detail.getMainId())
                        .andProcessEqualTo(detail.getProcess())
                        .andProcessDetailIdEqualTo(processDetailId)
                        .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                User user = userMapper.selectByPrimaryKey(detail.getTypeValue());
                detail.setUsername(user.getUsername());
                detail.setLoginName(user.getLoginName());
                List<WorkflowApproveDetail> workflowApproveDetails = workflowApproveDetailMapper.selectByExample(example);
                if (workflowApproveDetails.size() > 0) {
                    WorkflowApproveDetail approveDetail = workflowApproveDetails.get(0);
                    if (!StringUtils.isEmpty(approveDetail.getApproveType())) {
                        detail.setEnableFlag(approveDetail.getApproveType());
                        detail.setApproveMsg(approveDetail.getApproveMsg());
                        detail.setApproveTime(Tools.getCenternTime(approveDetail.getApproveDate()));
                    }
                }
            }
        }
        return workflowConfigDetails;
    }

    public List<WorkflowConfigDetail> getProgressByMaterialId(String defaultNumber) throws Exception {
        WorkflowProcessDetailExample example = new WorkflowProcessDetailExample();
        example.createCriteria().andSysOwnerCpyEqualTo(defaultNumber)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<WorkflowProcessDetail> processDetailList = workflowProcessDetailMapper.selectByExample(example);
        if (processDetailList!=null && processDetailList.size()>0){
            WorkflowProcessDetail processDetail = processDetailList.get(0);
            return getProgressInfo(processDetail.getDefineDetailId(), processDetail.getId());
        }else {
            WorkflowApproveDetailExample approveDetailExample = new WorkflowApproveDetailExample();
            approveDetailExample.createCriteria()
                    .andSysOwnerCpyEqualTo(defaultNumber)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            approveDetailExample.setOrderByClause("approve_date desc");
            List<WorkflowApproveDetail> workflowApproveDetails = workflowApproveDetailMapper.selectByExample(approveDetailExample);
            if (workflowApproveDetails!=null&&workflowApproveDetails.size() > 0){
                WorkflowApproveDetail approveDetail = workflowApproveDetails.get(0);
                return getProgressInfo(approveDetail.getConfigId(), approveDetail.getProcessDetailId());
            }
        }
        return null;
    }
}
